<?php

/**
 * Class BaseUser
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $password_hash
 * @property string $email
 * @property integer $status
 * @property integer $create_time
 * @property integer $update_time
 * @property integer $login_time
 * @property string $token
 * @property string $nickname
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @package common.models
 * @since 1.0
 */
abstract class BaseUser extends CActiveRecord
{
	/**
	 * @var integer
	 */
	const STATUS_NORMAL = 0;

	/**
	 * @var integer
	 */
	const STATUS_BLOCK = 3;

	/**
	 * @var integer
	 */
	const STATUS_NOT_ACTIVE = 1;

	/**
	 * @var string
	 */
	public $password_repeat;

	/**
	 * @var string
	 */
	private $_password;

	/**
	 * 验证规则
	 *
	 * @return array
	 */
	public function rules()
	{
		return array(
			array('username, email', 'required'),

			array('password, password_repeat', 'required', 'on' => 'insert'),
			array('password', 'safe'),
			array('password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => '{attribute} 不一致'),

			array('username', 'match', 'pattern' => '|^[0-9a-z\-_]{5,16}|i', 'message' => '{attribute} 只能包含字母和数字 、-、 _， 长度在5-16之间.'),
			array('nickname', 'length', 'max' => 16),

			array('email', 'length', 'max' => 128),
			array('email', 'email'),

			array('status', 'in', 'range' => array(self::STATUS_NORMAL, self::STATUS_NOT_ACTIVE, self::STATUS_BLOCK)),

			array('username, email', 'unique'),
			array('update_time, login_time, create_time, id', 'safe', 'on' => 'search'),
		);
	}

	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'username' => '用户名',
			'password' => '密码',
			'password_repeat' => '确认密码',
			'nickname' => '昵称',
			'email' => '邮箱',
			'status' => '状态',
			'create_time' => '创建时间',
			'update_time' => '更新时间',
			'login_time' => '登录时间',
		);
	}

	/**
	 * 获取状态文本
	 *
	 * @return string
	 */
	public function getStatusStr()
	{
		$statusList = $this->getStatusList();
		return isset($statusList[$this->status]) ? $statusList[$this->status] : '未知';
	}

	/**
	 * 获取状态列表
	 *
	 * @return array
	 */
	public function getStatusList()
	{
		return array(
			self::STATUS_NORMAL => '正常',
			self::STATUS_NOT_ACTIVE => '未激活',
			self::STATUS_BLOCK => '锁定',
		);
	}

	/**
	 * 获取密码
	 *
	 * @return string
	 */
	public function getPassword()
	{
		return $this->_password;
	}

	/**
	 * 设置密码
	 *
	 * @param $password
	 */
	public function setPassword($password)
	{
		if ($password !== '') {
			$this->password_hash = YPasswordHelper::hashPassword($password);
			$this->_password = $password;
		}
	}

	/**
	 * 验证密码
	 *
	 * @param $password
	 * @return bool
	 */
	public function validatePassword($password)
	{
		return YPasswordHelper::verifyPassword($password, $this->password_hash);
	}

	/**
	 * 生成一个token
	 *
	 * @return string
	 */
	public function generateToken()
	{
		$this->token = Yii::app()->getSecurityManager()->generateRandomString(32) . '_' . time();
	}

	/**
	 * @param $token
	 * @return BaseUser|null
	 */
	public function findByPasswordResetToken($token)
	{
		if (isset(Yii::app()->params['user.passwordResetTokenExpire'])) {
			$expire = Yii::app()->params['user.passwordResetTokenExpire'];
		} else {
			$expire = 3600;
		}

		$parts = explode('_', $token);
		$timestamp = (int)end($parts);
		if ($timestamp + $expire < time()) {
			// token expired
			return null;
		}

		return $this->findByAttributes(array(
			'token' => $token,
			'status' => self::STATUS_NORMAL,
		));
	}

	/**
	 * 根据token查找用户
	 *
	 * @param $token
	 * @return BaseUser
	 */
	public function findByToken($token)
	{
		return $this->findByAttributes(array(
			'token' => $token
		));
	}

	/**
	 * 移除token
	 */
	public function removeToken()
	{
		$this->token = '';
	}

	/**
	 * 保存之前
	 *
	 * @return bool
	 */
	protected function beforeSave()
	{
		if (parent::beforeSave()) {
			if ($this->isNewRecord) {
				$this->create_time = time();
			}
			$this->update_time = time();

			if ($this->hasAttribute('nickname') && !trim($this->nickname)) {
				$this->nickname = $this->username;
			}

			return true;
		} else {
			return false;
		}
	}
}
